package com.wangxiaotao.springcloud.alibaba.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.wangxiaotao.springcloud.alibaba.service.PaymentService;
import com.wangxiaotao.springcloud.entities.CommonResult;
import com.wangxiaotao.springcloud.entities.Payment;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RequiredArgsConstructor
@RestController
@Slf4j
public class CirleBreakerController {
    private final RestTemplate restTemplate;
    private final PaymentService paymentService;

    public static final String SERVICE_URL = "http://nacos-payment-provider";

    @Value("${server-url.nacos-user-service}")
    private String serverURL;

    @RequestMapping("/consumer/fallback/{id}")
//    @SentinelResource(value = "fallback")
//    @SentinelResource(value = "fallback",fallback = "handlerFallback")
//    @SentinelResource(value = "fallback",blockHandler = "blockHandler")
    /**
     * fallback:处理业务异常
     * blockHandler:只负责sentinel控制违规异常
     * exceptionsToIgnore:忽略的异常
     */
    @SentinelResource(value = "fallback",fallback = "handlerFallback",blockHandler = "blockHandler" )
    public CommonResult<Payment> fallback(@PathVariable Long id){
        CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL+"/paymentSQL/"+id,CommonResult.class,id);
        if (id == 4){
            throw new IllegalArgumentException("IllegalArgumentException,非法参数");
        }else if (result.getData() == null){
            throw new NullPointerException("NullPointerException,空指针异常");
        }
        return  result;
    }
    public CommonResult<Payment> handlerFallback(@PathVariable Long id,Throwable e){
        Payment payment = new Payment(id,null);
        return new CommonResult(444,"fallback---业务异常，抛出："+e.getMessage(),payment);
    }

    public CommonResult<Payment> blockHandler(@PathVariable Long id,Throwable e){
        Payment payment = new Payment(id,null);
        return new CommonResult(444,"blockHandler---sentinel控制违规异常,抛出："+e.getMessage(),payment);
    }

    @GetMapping("/consumer/paymentSQL/{id}")
    CommonResult<Payment> paymentSQL(@PathVariable("id") Long id){
        return paymentService.paymentSQL(id);
    }

}
